const app = getApp()

import Dialog from '@vant/weapp/dialog/dialog';
import Notify from '@vant/weapp/notify/notify';

import {
    showroomDetailRq,
    listByTypeRq,
    saveShowRoomRecordRq
} from "../../../../api/meeting/exhibition.js"

import {
    selfFormatTimeYMD,
    selfFormatTimeHM,
    twoTimeInterval
} from "../../../../utils/util.js"


Page({

    /**
     * 页面的初始数据
     */
    data: {
        IMG_NAME: app.IMG_NAME,
        protocolFlag: true,
        protocolTitle: '《展厅服务协议》',
        id: null,
        bannerList: [],
        detail: {},
        userData: {},
        startTime: null,
        endTime: null,
        selectDay: null,
        selectCountTime: null,
        // 选择参观目的
        visitTypeShow: false,
        visitTypeList: [],
        // 来参观人员-dialog
        dialogShow: false,
        dialogName: null,
        dialogJob: null,
        dialogPhone: null,
        // 来参观人员
        personList: [],
        // 拟参观区域
        visitAreaShow: false,
        visitAreaList: [],
        visitAreaSelectList: [],
        visitAreaSelectContent: null,
        // 倒计时id
        meetingTimeId: null,
        // 提交数据
        formData: {
            showroomId: null, // 展厅id
            userId: null, // 用户id
            startTime: null, // 开始时间
            endDate: null, // 结束时间
            title: null, // 展厅主题
            persons: null, // 来参观人员
            visitType: null, // 参观目的
            visitTypeName: null, // 参观目的-name
            explainNeedType: 0, // 讲解需求
            explainNeedTypeBoolean: false, // 讲解需求-boolean
            meetingNeedType: 0, // 是否需要会议室
            meetingNeedTypeBoolean: false, // 是否需要会议室-boolean
            photographType: 0, // 摄影需求
            photographTypeBoolean: false, // 摄影需求-boolean
            remake: null, // 备注
            visitArea: null, // 拟参观区域
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('onLoad', options);
        let _this = this;
        let selectCountTime = selfFormatTimeHM(options.startTime) + "-" + selfFormatTimeHM(options.endTime) + ' 共计' + twoTimeInterval(options.startTime, options.endTime)
        _this.setData({
            ...options,
            userData: wx.getStorageSync('user'),
            selectDay: selfFormatTimeYMD(options.startTime),
            selectCountTime
        })
        // 表单数据初始化
        let formData = _this.data.formData;
        formData.showroomId = _this.data.id; // 展厅id
        formData.userId = _this.data.userData.id // 用户id
        formData.startTime = _this.data.startTime // 开始时间
        formData.endDate = _this.data.endTime // 结束时间
        // 详细信息
        _this.getDetail();
        // 获取字典数据
        _this.getDictData();
    },

    // 详细信息
    getDetail() {
        let _this = this;
        showroomDetailRq(this.data.id).then(res => {
            let detail = res.data;
            let bannerList = []
            if (detail.indoorPicUrl) {
                try {
                   bannerList = JSON.parse(detail.indoorPicUrl).map(item=>item.url)
                } catch (error) {
                    console.log(`JSON error : ${error}`);
                }
            }
            _this.setData({
                detail,
                bannerList
            })
        })
    },

    // 获取字典数据
    getDictData() {
        let _this = this
        listByTypeRq({
            "dictType": "visit_type"
        }).then(res => {
            console.log('getDictData', res);
            let visitTypeList = res.data.map(item => {
                return {
                    name: item.dictLabel,
                    value: item.dictValue,
                }
            })
            _this.setData({
                visitTypeList
            })
        })
        // 拟参观区域字典
        listByTypeRq({
            "dictType": "visit_area"
        }).then(res => {
            console.log('getDictData', res);
            let visitAreaList = res.data.map(item => {
                return {
                    name: item.dictLabel,
                    value: item.dictValue,
                }
            })
            _this.setData({
                visitAreaList
            })
        })
    },

    // input监听
    inputChange(e) {
        console.log('inputChange', e);
        let _this = this;
        let formData = _this.data.formData;
        formData[e.currentTarget.dataset.name] = e.detail
        _this.setData({
            formData
        })
    },

    // switch监听
    switchChange(e) {
        console.log('switchChange', e);
        let _this = this;
        let status = e.detail;
        let formData = _this.data.formData;
        formData[e.currentTarget.dataset.name + 'Boolean'] = status
        if (status) {
            formData[e.currentTarget.dataset.name] = 1
        } else {
            formData[e.currentTarget.dataset.name] = 0
        }
        _this.setData({
            formData
        })
    },

    // 显示-参观目的
    showVisitType() {
        let _this = this;
        _this.setData({
            visitTypeShow: true
        })
    },

    // 隐藏-参观目的
    hideVisitType() {
        let _this = this;
        _this.setData({
            visitTypeShow: false
        })
    },

    // 选择-参观目的
    selectVisitType(e) {
        console.log('selectVisitType', e);
        let _this = this;
        let formData = _this.data.formData;
        formData.visitType = e.detail.value; // 参观目的
        formData.visitTypeName = e.detail.name; // 参观目的-name
        _this.setData({
            formData
        })
    },

    // 显示-dialog
    dialogUnfold() {
        let _this = this;
        _this.setData({
            dialogShow: true
        })
    },
    // 取消-dialog 
    dialogCancel() {
        let _this = this;
        _this.setData({
            dialogShow: false
        })
    },

    // 提交-dialog 
    dialogSubmit() {
        let _this = this;
        let name = _this.data.dialogName
        let job = _this.data.dialogJob
        let phone = _this.data.dialogPhone
        if (!name) {
            // 显示错误信息
            _this.showErrMsg('请输入姓名!')
            return;
        }
        if (!job) {
            // 显示错误信息
            _this.showErrMsg('请输入职务!')
            return;
        }
        // 来参观人员
        let personList = _this.data.personList;
        personList.push({
            id: new Date().getTime(),
            name,
            job,
            phone
        })
        _this.setData({
            personList,
            dialogShow: false,
            dialogName: null,
            dialogJob: null,
            dialogPhone: null,
        })
    },

    // 删除来参观人员
    removePerson(e) {
        console.log('removePerson', e);
        let _this = this;
        let id = e.currentTarget.dataset.id
        let personList = _this.data.personList.filter(item => item.id != id)
        _this.setData({
            personList
        })
    },

    // input监听-dialog
    dialogInputChange(e) {
        console.log('dialogInputChange', e);
        let _this = this;
        let data = _this.data;
        data[e.currentTarget.dataset.name] = e.detail
        _this.setData(data)
    },

    // 显示错误信息
    showErrMsg(msg) {
        // 错误提示
        Notify({
            type: 'danger',
            message: msg
        });
    },

    // 拟参观区域
    visitAreaChange(event) {
        let _this = this;
        let visitAreaSelectList = event.detail;
        let visitAreaSelectContent = null;
        if (visitAreaSelectList && visitAreaSelectList.length > 0) {
            visitAreaSelectContent = visitAreaSelectList.join(',')
        } else {
            visitAreaSelectContent = null;
        }
        _this.setData({
            visitAreaSelectList,
            visitAreaSelectContent
        });
    },

    // 拟参观区域-关闭
    visitAreaClose() {
        this.setData({
            visitAreaShow: false,
        });
    },

    // 拟参观区域-显示
    visitAreaShow() {
        this.setData({
            visitAreaShow: true,
        });
    },

    // 协议点击
    protocolChange() {
        let _this = this;
        _this.setData({
            protocolFlag: !_this.data.protocolFlag
        });
    },

    // 跳转协议
    jumpProtocol() {
        let _this = this;
        wx.navigateTo({
            url: "/pages/meeting/meetingRoom/meetingProtocol/meetingProtocol?title=" + _this.data.protocolTitle,
        })
    },

    // 提交
    submitData() {
        let _this = this
        let formData = _this.data.formData;
        // 参数校验
        //
        // 展厅主题
        if (!formData.title) {
            // 错误提示
            _this.showErrMsg('请输入展厅主题!');
            return;
        }
        // 来参观人员
        if (_this.data.personList && _this.data.personList.length > 0) {
            formData.persons = JSON.stringify(_this.data.personList)
        } else {
            // 错误提示
            _this.showErrMsg('请添加来参观人员!');
            return;
        }
        // 参观目的
        if (!formData.visitType) {
            // 错误提示
            _this.showErrMsg('请选择参观目的!');
            return;
        }
        // 拟参观区域
        if (_this.data.visitAreaSelectList && _this.data.visitAreaSelectList.length > 0) {
            formData.visitArea = _this.data.visitAreaSelectList.join(',')
        } else {
            // 错误提示
            _this.showErrMsg('请选择拟参观区域!');
            return;
        }
        // 同意协议
        if (!_this.data.protocolFlag) {
            // 错误提示
            _this.showErrMsg(`请同意${_this.data.protocolTitle}!`);
            return;
        }

        // 提交数据
        saveShowRoomRecordRq(formData).then(res => {
            console.log('saveShowRoomRecordRq', res);
            if (res.code == 0) {
                // 需要会议室
                if (formData.meetingNeedTypeBoolean) {
                    Dialog.alert({
                        title: '提示',
                        message: '预约提交成功,即将为您跳转至会议室预约页面',
                    }).then(() => {
                        wx.reLaunch({
                            url: "/pages/meeting/meetingReservation/meetingReservation",
                        })
                    });
                    // 设置倒计时跳转
                    let meetingTimeId = setTimeout(() => {
                        wx.reLaunch({
                            url: "/pages/meeting/meetingReservation/meetingReservation",
                        })
                    }, 2000);
                    _this.setData({
                        meetingTimeId
                    })
                } else {
                    wx.reLaunch({
                        url: "/pages/meeting/reservationRecord/exhibitionRecord/list/list",
                    })
                }
            } else {
                _this.showErrMsg(res.msg)
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log('onShow');

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('onUnload', '生命周期函数--监听页面卸载');
        let _this = this;
        // 删除倒计时
        if(_this.data.meetingTimeId){
            clearTimeout(_this.data.meetingTimeId)
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})